<?php
/**
 * 
 * @author tangbl
 *
 */
class WechatAction{
	
	private $data = NULL;
	
	public function index(){
		
		import('ORG.Wechat.ThinkWechat');
		
		$TOKEN  = get_syscfig_key('wxtoken');
		$weixin = new ThinkWechat($TOKEN);
		$data   = $weixin->request();
		
		$this->data = $data;
		
		/*
		$data['MsgType']    = 'event';// location event
		$data['Event']      = 'subscribe';
		$data['MsgType']    = 'text';
		$data['Content']    = '你好';
		$data['FromUserName'] = '123123123123';
		$data['MsgType']    = 'event';// location event
		$data['Event']      = 'subscribe';
		$data['Location_Y'] = '113.997069';
		$data['Location_X'] = '28.140119';
		$data['Scale']      = '18';
		dump($content);
		echo $type;
		*/
		
		list($content, $type) = $this->reply($data);
		//dump($content);
		$weixin->response($content, $type);	
	}
	
	private function reply($data){
		$log   = D("Wxlog");
		$logid = $log->add($data);
		
		$reply   = D("Admin://Reply");
		if('text' == $data['MsgType']){
			
			$text  = trim($data['Content']);
			$rtalk = $log->replyTalk($text);//微信会话
			if($rtalk){
				return $rtalk;
			}else{
				$map['keywords'] = $text;
				$rows  = $reply->getReplyRowlyByMap($map);
				if(empty($rows['id'])){//无匹配内容
					$rows = $reply->getReplyRowlyByMap(array("reply_type"=>6));
				}
			}
			
		} elseif('event' == $data['MsgType']){
			$map['reply_type'] = 3 ;
			if('subscribe' == $data['Event']){
				$log->subscribe($data);//用户关注
				$map['event_type'] = 1 ;
			}elseif('unsubscribe' == $data['Event']){
				$log->unsubscribe($data);//用户取消关注
				$map['event_type'] = 2 ;
			}elseif("CLICK" == $data['Event']){
				$map['event_type']  = 2 ;
				$map['event_value'] = $data['EventKey'] ;
			}
			$rows  = $reply->getReplyRowlyByMap($map);	
			
		} elseif('image' == $data['MsgType']) {
			$map['reply_type'] = 4 ;
			$rows  = $reply->getReplyRowlyByMap($map);
			
		} elseif('location' == $data['MsgType']) {
			$map['reply_type'] = 2 ;
			$rows  = $reply->getReplyRowByLocation($map,$data);
		}elseif("link" == $data['MsgType']){
			return $log->handleUrl($data);
		}else {
			exit;	
		}
		return $this->cache_reply($rows['reply_solevar'],$rows['retype']);;
	}
	
	//缓存回复
	private function cache_reply($solevar,$type){
		$cachename = 'Reply_Cache'.$solevar;
		$lists     = S($cachename);
		$openon    = C("WECHAT_AUTH_ON");
		
		if($openon && "news"==$type){
			$lists = $this->create_url_openid($lists);
		}
		return array($lists, $type);
	}
	
	//图文链接带上openid
	private function create_url_openid($lists){
		
		$data 	   = $this->data;
		$open_cfg  = C("OPEN_ID_URL");
		$open_id   = myencrypt($data['FromUserName']);
		$open_url  = $open_cfg.$open_id;
		
		$rows = array();
		foreach($lists as $k=>$v){
			$v['Url']  = $v['Url'].$open_url;
			$rows[$k]  = $v;
		}
		return $rows;
	}
}
